package com.motorhome.manage.controller;

import com.google.code.kaptcha.Producer;
import com.motorhome.base.cache.MemcachedCache;
import com.motorhome.base.session.CookieSession;
import com.motorhome.manage.common.statics.ManageStatics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.UUID;

/**
 * @author: John
 */
@Controller
public class KaptchaController {

    @Autowired
    private Producer captchaProducer;

    @Autowired
    private MemcachedCache cache;

    @RequestMapping(value = "/kaptcha")
    public void kaptcha(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //设置响应头
        response.setDateHeader("Expires", 0);
        response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        response.addHeader("Cache-Control", "post-check=0, pre-check=0");
        response.setHeader("Pragma", "no-cache");
        response.setContentType("image/jpeg");

        String kaptchaCacheKey = UUID.randomUUID().toString();
        CookieSession sessions = new CookieSession(request, response, ManageStatics.KAPTCHA_SESSION_KEY);
        sessions.put(ManageStatics.KAPTCHA_CACHE_KEY, kaptchaCacheKey);
        sessions.flush(response);

        String capText = captchaProducer.createText();
        cache.set(kaptchaCacheKey, capText, "5min");

        BufferedImage bi = captchaProducer.createImage(capText);
        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(bi, "jpg", out);
        try {
            out.flush();
        } finally {
            out.close();
        }

    }

}
